package com.ku.pksu.bornegaarden.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class HTTPFetcher
{

	private final String TAG = "HTTPFetcher";
	private final String URL = "http://www.bornegaardenblistrup.dk/";
	private Context cxt;

	public HTTPFetcher(Context context){
		cxt = context;
	}

	public HTTPFetcher(String urlPart)
	{
		fetch(urlPart);
	}
	

	public boolean fetch(String urlPart){
		String current = lastUpdated(URL + urlPart + ".asp", true);
		String last = lastUpdated(urlPart + ".asp", false);

		if((current != null) && current.equals(last) == false)
		{
			//			downloadFile("http://www.bornegaardenblistrup.dk/admin/inc/webstyle.min.css", "webstyle.min.css", null, false);
			downloadFile(URL + "admin/inc/default.min.js", "default.min.js", null, false);
			downloadFile(URL + "layout/style_content.css", "style_content.css", null, false);

			String html = "<!--" + current + "-->\n" +
					downloadHTML(URL + urlPart + ".asp",
							"<!-- vvv INDHOLD START vvv -->",
							"<!-- ^^^ INDHOLD SLUT ^^^ -->");

			downloadImages(html);

			createFiles(urlPart + ".asp", html);
		}
		return true;
	}

	private String lastUpdated(String input, boolean URL)
	{
		BufferedReader reader;
		String temp, relavant = "";

		try {
			if(URL == true)
			{
				URL url = new URL(input);
				reader = new BufferedReader(new InputStreamReader(url.openStream()));
			}
			else
			{
				try {
					reader = new BufferedReader(new FileReader(input));
				}
				catch(IOException e)
				{
					return "";
				}
			}

			boolean found = false;
			while((temp = reader.readLine()) != null && found == false)
			{
				if(temp.indexOf("sidstopdateret") >= 0)
				{
					if(temp.indexOf("<!--") >= 0)
						relavant = temp.substring(4, temp.length() - 3);

					else
						relavant = temp;

					found = true;
				}
			}

			reader.close();
		}
		catch(MalformedURLException e)
		{
			Log.e(TAG, "Download Error - " + e);
			return null;
		}
		catch(IOException e)
		{
			Log.e(TAG, "IO Error - " + e);
			return null;
		}

		return relavant;
	}

	private String downloadHTML(String inputURL, String startHTML, String endHTML)
	{
		URL url;
		BufferedReader reader;
		String temp, relavant = "";
		boolean download = false;

		try {
			url = new URL(inputURL);

			reader = new BufferedReader(new InputStreamReader(url.openStream()));

			while((temp = reader.readLine()) != null)
			{
				if(download == false && temp.indexOf(startHTML) >= 0)
				{
					download = true;
				}
				else if(download == true)
				{
					if(temp.indexOf(endHTML) >= 0)
						download = false;

					else
						relavant += containsMail(temp) + "\n";
				}
			}

			reader.close();
		}
		catch(MalformedURLException e)
		{
			return "Error - URL not found - " + e;
		}
		catch(IOException e)
		{
			return "Error - IO - " + e;
		}

		return removeParagraph(relavant);
	}

	private void downloadImages(String html)
	{
		if(html != null) {
			String locateString = "img src=\"";

			int locateLength = locateString.length();
			int indexEnd, nextIndex = 0;

			while((nextIndex = html.indexOf(locateString, nextIndex) + locateLength) != -1 + locateLength)
			{
				indexEnd = html.indexOf("\"", nextIndex);

				String imageName = html.substring(nextIndex, indexEnd);

				downloadFile(URL + imageName, imageName, "pics", false);
			}
		} else {
			Log.e(TAG, "html returned was null");
		}
	}

	private void createFiles(String filename, String content)
	{
		try {
			FileOutputStream fos = cxt.openFileOutput(filename, Context.MODE_PRIVATE);
			BufferedOutputStream out = new BufferedOutputStream(fos);

			out.write("<html>\n<head>\n".getBytes());

			out.write(("<link rel=\"stylesheet\" type=\"text/css\" href=\"webstyle.min.css?rnd=23\" />\n" +
					"<link rel=\"stylesheet\" type=\"text/css\" href=\"style_content.css?rnd=23\" />\n" +
					"<script type=\"text/javascript\" src=\"default.min.js?rnd=23\"></script>").getBytes());

			out.write("\n</head>\n\n<body>\n<div id=\"content\">\n".getBytes());

			out.write(content.getBytes());

			out.write("</div>\n</body>\n</html>".getBytes());

			out.flush();

			out.close();
		}
		catch(Exception e)
		{
			Log.e(TAG, "Create Error - " + e);
		}
	}

	private void downloadFile(String url, String filename, String pathToFile, boolean override)
	{
		if(pathToFile != null)
		{
			//			File file = cxt.getDir(pathToFile, Context.MODE_WORLD_WRITEABLE);
			File file = new File(cxt.getFilesDir().getAbsolutePath() + File.separator + pathToFile);
			if (!file.exists()){
				Boolean valid = file.mkdir();
				Log.e("Create dir", valid ? "pics dir created" : "Failed to create dir");
			}
			//			File dir = new File(cxt.getFilesDir() + "/" + pathToFile);
			//			if (cxt.getDir(pathToFile, Context.MODE_PRIVATE) == null) 
			//			if(dir.mkdirs() == false)
			//				Log.e(TAG, pathToFile + " not created - " + cxt.getFilesDir());
		}

		File fileCheck = new File(filename);

		if(fileCheck.exists() == false || override == true)
		{
			BufferedInputStream in = null;
			BufferedOutputStream out = null;
			try
			{
				FileOutputStream fos = new FileOutputStream(new File(cxt.getFilesDir() + "/" + filename));
				//				FileOutputStream fos = cxt.openFileOutput(cxt.getFilesDir() + "/" + filename, Context.MODE_PRIVATE);
				in = new BufferedInputStream(new URL(url).openStream());
				out = new BufferedOutputStream(fos);

				byte data[] = new byte[1024];
				int count;
				while((count = in.read(data, 0, 1024)) != -1)
					out.write(data, 0, count);

				in.close();
				out.flush();
				out.close();
			}
			catch(Exception e)
			{
				Log.e(TAG, "Download Error - " + e);
			}
		}
	}

	private String containsMail(String s){
		if (s.contains("href=\"mailto:")){

			String mail = s.split("mailto:")[1].split("\"")[0];
			String[] sub = s.split("</a>");
			s = sub[0].split("<a")[0] + "e-mail adr. <a" + sub[0].split("<a")[1] + mail + "</a>" + sub[1];
		}

		if (s.contains("encodemail")){
			String sub = s.split("encodemail")[1].split(",")[2];
			String mail = sub.substring(1, sub.length()-1) + "@bornegaarden.dk";

			String start = "<script type=\"text/javascript\">";
			String end = "</script>";
			String[] subsub = s.split(start);
			s = subsub[0] + "<a href=\"mailto:" + mail + "\">" + mail + "</a>" + subsub[1].split(end)[1];
		}

		return s;
	}

	private String removeParagraph(String s){
		String sub[] = s.split("<p>&nbsp;</p>");
		s = "";
		for(String ss : sub){
			s = s.concat(ss);
		}
		return s;
	}
}

